﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Filters;
using STF.Blog.WebApp.Areas.ForumManage.Models.Users;
using STF.Blog.WebApp.Areas.ForumManage.Models.UsersInfo;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class UsersInfoController : Controller
    {
        private IUsersInfoService _usInfoSvc;
        private IUsersService _usersSvc;
        private IWebHostEnvironment _iwe;
        public UsersInfoController(IUsersInfoService usInfoSvc, IUsersService usersSvc, IWebHostEnvironment iwe)
        {
            _usInfoSvc = usInfoSvc;
            _usersSvc = usersSvc;
            _iwe = iwe;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search , int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _usInfoSvc.GetByNameAsync(search);
            var dataList = new List<UsersInfoListViewModel>();
            foreach (var item in data) 
            {
                var model = new UsersInfoListViewModel
                {
                    Id = item.Id,
                    RealName = item.RealName,
                    Birthday = item.Birthday.ToString("yyyy年MM月dd日"),
                    Gender = item.Gender,
                    WeChat = item.WeChat,
                    Tel = item.Tel,
                    Address = item.Address,
                    Photo = item.Photo,
                    Amount = item.Amount,
                    UsersTitle = await GetUsersInfoTitle(item.Uid),
                    UpdateTime = item.UpdateTime
                };
                dataList.Add(model);
            }

            ViewBag.Search = search;
            var pages = await dataList.ToPagedListAsync(page,PageConfig.PageSize);

            return View(pages);
        }

        public async Task<IActionResult> Add() 
        {
            BindUsersList(null);

            return View(new UsersInfoAddViewModel());
        }

        public async Task<IActionResult> Add(UsersInfoAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                string imageName = await UploadFiles(model.Photo,@"\ImageHead\UsersInfo");
                if (string.IsNullOrEmpty(imageName))
                {
                    imageName = "123.jpg";
                }
                var res = await _usInfoSvc.AddUsersInfoAsync(model.RealName,DateTime.Parse(model.Birthday),
                    (int)model.Gender,model.WeChat,model.Tel,model.Address,imageName,model.Amount,model.UsersId);

                if (res > 0) 
                {
                    return Redirect("~/ForumManage/UsersInfo/Index");
                }
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _usInfoSvc.PutTrashAsync(id);
            return Redirect("~ForumManage/UsersInfo/Index");
        }


        private async Task<string> GetUsersInfoTitle(int id)
        {
            var data = await _usersSvc.GetByIdAsync(id);
            return data.NickName;
        }

        private async Task BindUsersList(int? usersId) 
        {
            var data = await _usersSvc.GetAllUsersAsync();
            var dataList = data.Select(us => new UsersListViewModel
            {
                Id = us.Id,
                NickName = us.NickName
            });

            if(usersId == null)
                ViewBag.UsersList = new SelectList(dataList,"Id","Title");

            ViewBag.UsersList = new SelectList(dataList, "Id", "Title", usersId);
        }

        private async Task<string> UploadFiles(IFormFile image, string url) 
        {
            string imageName = "";
            if (image != null && image.FileName != null) 
            {
                imageName = DateTime.Now.ToString("yyyyMMddHHmmss") + 
                            image.FileName.Substring(image.FileName.LastIndexOf("."));

                string imagePath = _iwe.WebRootPath + url;
                string path = Path.Combine(imagePath, imageName);
                image.CopyTo(new FileStream(path, FileMode.Create));
            }
            return imageName;
        }

    }     
}

